<?php

namespace app\common\command;

use app\common\tools\Str;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use tp5er\Backup;

/**
 * 清空数据库表
 * Class ClearDatabase
 * @package app\common\command
 */
class ClearDatabase extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('database:clear')->setDescription('clear database');
        // 设置参数
        $this->addOption('table', 1, Option::VALUE_OPTIONAL, "deleted table name");

    }

    protected function execute(Input $input, Output $output)
    {
        $table = $input->getOption('table');
        $table = Str::uncamelize($table);
        //获取表白名单
        $white_table = config('white_table.');

        //获取数据库所有表
        $tables = Db::query('show tables');
        $database = Db::getConfig('database');
        $mark = 'Tables_in_' . $database;
        if (is_null($table)) {
            //筛选可以清空的表sql
            $clearTableSql = [];
            foreach ($tables as $table) {
                if (!in_array($table[$mark], $white_table)) {
                    $clearTableSql[] = "truncate table {$table[$mark]}";
                }
            }
            $backupsConfig = [
                'path'=>app()->getRootPath().'backup/',//数据库备份路径
            ];
            //备份数据库
            $db = new Backup($backupsConfig);
            $time = time();
            $file = ['name' => date('Ymd-His', $time), 'part' => 1];
            //获取数据表列表
            set_time_limit(0);
            $tableList = $db->dataList();
            $is_del = false;
            foreach ($tableList as $k => $v) {
                $start = $db->setFile($file)->backup($v['name'], 0);
                if ($start == 0) {
                    continue;
                } else {
                    $is_del = true;
                    break;
                }
            }
            if (!$is_del) {
                //清空
                if ($this->output->confirm($this->input, 'Confirm to clear all data? [y]/n')) {
                    Db::batchQuery($clearTableSql);
                    $output->writeln("<info>tables all clear successfully!</info>");
                }
            }

        } else {
            $tables = array_column($tables, $mark);
            if (in_array($table, $tables)) {
                $clearTableSql[] = "truncate table {$table}";
                if ($this->output->confirm($this->input, "Confirm to clear {$table} data? [y]/n")) {
                    //清空
                    Db::batchQuery($clearTableSql);
                    $output->writeln("<info>{$table} delete successfully!</info>");
                }
            } else {
                $output->writeln("<error>{$table} not exist!</error>");
            }
        }
    }
}
